const { getRedis, setRedis } = require('../db/redis');

/**
 * 获取 request 中的 postData
 * @param req
 * @param res
 * @returns {Promise<any>}
 */
const getPostData = (req, res) => {
    const method = req.method;

    return new Promise((resolve, reject) => {
        if (method !== 'POST') return resolve({});
        if (req.headers['content-type'] !== 'application/json') return resolve({});

        let chunkString = '';

        req.on('data', chunk => {
            chunkString += chunk.toString();
        });

        req.on('end', () => {
            const postData = chunkString ? JSON.parse(chunkString) : {};
            resolve(postData);
        })
    });
};

/**
 * 以对象的形式获取到 request.headers 中的 cookie
 * @param req
 * @param res
 */
const getCookie = (req, res) => {
    let result = {};
    const cookieString = req.headers.cookie;
    if (!cookieString) return result;
    const arr = cookieString.split(';');
    arr.forEach(item => {
        const itemArr = item.split('=');
        let key = itemArr[0] || '';
        let value = itemArr[1] || '';
        key = key.trim();
        value = value.trim();
        result[key] = value;
    });
    return result;
};

/**
 * 设置 cookie 的过期时间
 * @param day
 * @returns {*}
 */
const getCookieExpires = (day = 1) => {
    const date = new Date();
    date.setTime(date.getTime() + (day * 24 * 60 * 60 * 1000));
    return date.toGMTString();
};

const checkLogin = req => {
    const cookie = req.cookie;
    const { token } = cookie;
    return getRedis(token).then(userData => {
        if (userData) {
           return true;
        } else {
            return false;
        }
    }).catch(e => {
        console.error(`get redis failed: ${e}`);
    })
};


module.exports = {
    getPostData,
    getCookie,
    getCookieExpires,
    checkLogin
};
